<template>
	<div class="image-item" @click="viewImage">
		<div class="thumb">
			<img v-if="fileUrl" :src="fileUrl" class="thumb-img" alt="" loading="lazy" />
			<div v-else class="thumb-placeholder"></div>
		</div>
		<div class="caption">
			<p class="file-name">{{ originalName || props.title }}</p>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { listByIds } from "~/api/oss";

const props = defineProps({
  title: {
    type: String,
    default: '图片文件'
  },
  ossid: {
    type: [String, Number],
    required: true
  },
  originalName: {
    type: String,
    default: ''
  }
});

const fileUrl = ref('');
const originalName = ref('');
const loading = ref(true);

// 使用ossid获取文件URL
const fetchFileUrl = async () => {
  try {
    loading.value = true;
    const response = await listByIds(props.ossid.toString());
    if (response && response.data && response.data.length > 0) {
      fileUrl.value = response.data[0].url;
      originalName.value = response.data[0].originalName;
    }
  } catch (error) {
    console.error('获取图片文件URL失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchFileUrl();
});

const viewImage = () => {
  if (fileUrl.value) {
    window.open(fileUrl.value, '_blank');
  }
};
</script>

<style scoped lang="scss">
.image-item {
  width: 384px;
  background: #ffffff;
  border: 1px solid rgba(25, 30, 40, 0.08);
  box-shadow: 0 0 16px rgba(11, 13, 18, 0.06);
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-right: 24px;
  margin-bottom: 24px;
}

.image-item:hover {
  box-shadow: 0 4px 20px rgba(11, 13, 18, 0.12);
  transform: translateY(-2px);
}

.thumb {
  position: relative;
  height: 216px;
}

.thumb-img,
.thumb-placeholder {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.thumb-placeholder {
  background: #f5f5f5;
}

.caption {
  background: #ffffff;
  padding: 12px 16px;
}

.file-name {
  font-size: 14px;
  color: #191e28;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin: 0;
}
</style>
